﻿// ==UserScript==
// @library         library script for Tumblen3
// @namespace       http://watcher.moe-nifty.com/
// @description     This library is for rudimentary compatibility with Mozilla scripts and GreaseMonkey scripts
// ==/UserScript==
// $Header: /Tumblen3.root/Tumblen3/Tumblen3/scripts/library.js 11    08/10/16 23:22 Tsujimura543 $

// for debugging
var debugMode  = false;
var debugLevel = 0;
function alert0(str) {
    if (debugMode && debugLevel >= 0)
        alert(str);
}

function alert1(str) {
    if (debugMode && debugLevel >= 1)
        alert(str);
}

function alert2(str) {
    if (debugMode && debugLevel >= 2)
        alert(str);
}

function alert3(str) {
    if (debugMode && debugLevel >= 3)
        alert(str);
}

// forEach, map
(function () {
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}

if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/){
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i=0,res=[]; i<len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp,this[i],i,this);
    }
    return res;
  };
}
})();


// uneval()
//   via http://blog.livedoor.jp/dankogai/archives/50958256.html
(function(){
    // if uneval is predefined, skip it
    try{ eval('uneval'); return; }catch(e){};

    var protos = [];
    var uneval_asis = function(o){ return o.toString() };

    /* predefine objects where typeof(o) != 'object' */
    var name2uneval = {
        'boolean':uneval_asis,
        'number': uneval_asis,
        'string': function(o){
            return '\'' 
            + o.toString().replace(/[\\\"\']/g, function(m0){
                return '\\' + m0;
            }) 
            + '\'';
        },
        'undefined': function(o){ return 'undefined' },
        'function':uneval_asis
    };

    var uneval_default = function(o, np){
        var src = []; // a-ha!
        for (var p in o){
            if (!o.hasOwnProperty(p)) continue;
            src[src.length] = uneval(p)  + ':' + uneval(o[p], 1);
        }
        // parens needed to make eval() happy
        return np ? '{' + src.toString() + '}' : '({' + src.toString() + '})';
    };

    uneval_set = function(proto, name, func){
        protos[protos.length] = [ proto, name ];
        name2uneval[name] = func || uneval_default;
    };

    uneval_set(Array, 'array', function(o){
        var src = [];
        for (var i = 0, l = o.length; i < l; i++)
            src[i] = uneval(o[i]);
        return '[' + src.toString() + ']';
    });
    uneval_set(RegExp, 'regexp', uneval_asis);
    uneval_set(Date, 'date', function(o){
        return '(new Date(' + o.valueOf() + '))';
    });
    
    var typeName = function(o){
        // if (o === null) return 'null';
        var t = typeof o;
        if (t != 'object') return t;
        // we have to lenear-search. sigh.
        for (var i = 0, l = protos.length; i < l; i++){
            if (o instanceof  protos[i][0]) return protos[i][1];
        }
        return 'object';
    };
    
    uneval = function(o, np){
        // if (o.toSource) return o.toSource();
        if (o === null) return 'null';
        var func = name2uneval[typeName(o)] || uneval_default;
        return func(o, np);
    };
})();


// for exchange character sets
(function(){
    window.document.sjis2utf = function(str) {
        return window.external.sjis2utf(str);
    };

    window.document.euc2utf = function(str) {
        return window.external.euc2utf(str);
    };

    window.document.jis2utf = function(str) {
        return window.external.jis2utf(str);
    };
})();


var extern;
if (window.dialogArguments && window.dialogArguments.external) {
    extern = window.dialogArguments.external;
}
else if (window.external) {
    extern = window.external;
}

_tb_scriptName = extern.scriptName;
_tb_details = "";


function TB_setStatusText(text) {
    extern.setStatusText(_tb_scriptName, text);
}

function TB_scriptExists(name) {
    return extern.scriptExists(_tb_scriptName, name);
}

function TB_addScript(file, body, overwrite) {
    return extern.addScript(_tb_scriptName, file, body, overwrite);
}

function GM_registerMenuCommand() {
    if (arguments.length==2) {
        return extern.registerMenuCommand(_tb_scriptName,arguments[0],arguments[1],0,0);
    } else if (arguments.length>=3) {
        var shortcut = arguments[2];
        var flags = 0;
        if (shortcut.ctrl) {
            flags |= 0x1;
        }
        if (shortcut.alt) {
            flags |= 0x2;
        }
        if (shortcut.meta) {
            flags |= 0x4;
        }
        var key = shortcut.key.toUpperCase();

        if ((key>='A' && key<='Z') || (key>='0' && key<='9')) {
            return extern.registerMenuCommand(_tb_scriptName,arguments[0],arguments[1],flags,key);
        } else {
            return extern.registerMenuCommand(_tb_scriptName,arguments[0],arguments[1],0,0);
        }
    }
}

function GM_xmlhttpRequest(details) {
 // var xmlhttp = extern.getXmlHttpRequest(_tb_scriptName);
    var xmlhttp = (function() {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else
        if (window.ActiveXObject) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e2) {
                    return null;
                }
            }
        }
        else
            return null;
    })();
    
    if (!xmlhttp)
        return;

    xmlhttp.onreadystatechange = function() {
        var responseState = {
            responseXML:(xmlhttp.readyState==4 ? xmlhttp.responseText : ''),
            responseText:(xmlhttp.readyState==4 ? xmlhttp.responseText : ''),
            readyState:xmlhttp.readyState,
            responseHeaders:(xmlhttp.readyState==4 ? xmlhttp.getAllResponseHeaders() : ''),
            status:(xmlhttp.readyState==4 ? xmlhttp.status : 0),
            statusText:(xmlhttp.readyState==4 ? xmlhttp.statusText : '')
        }
        if (details["onreadystatechange"]) {
            details["onreadystatechange"](responseState);
        }
        if (xmlhttp.readyState==4) {
            if (details["onload"] && xmlhttp.status>=200 && xmlhttp.status<300) {
                /* [document.charset ではなく『details.url の取得結果の charset』で
                 *  処理を分岐すべき] -- 例えば、AutoPagerize の場合、ページ継ぎ足し
                 *  のときは document.charset でもいいけど、SITEINFO 取得時は 
                 *  『details.url の取得結果の charset』じゃないと駄目
                if (!document.charset.match(/utf-8/i)) {
                    if (document.charset.match(/shift_jis/i)) {
                        var str = sjis2utf(xmlhttp.responseText);
                        responseState.responseText = str;
                    }
                    else if (document.charset.match(/euc-jp/i)) {
                        var str = euc2utf(xmlhttp.responseText);
                        responseState.responseText = str;
                    }
                    else if (document.charset.match(/iso-2022-jp/i)) {
                        var str = jis2utf(xmlhttp.responseText);
                        responseState.responseText = str;
                    }
                    else
                        alert(document.charset + " から UTF-8 へ変換できません ＞＜ ");
                }
                */
                details["onload"](responseState);
            }
            if (details["onerror"] && (xmlhttp.status<200 || xmlhttp.status>=300)) {
                details["onerror"](responseState);
            }
        }
    }

    try {
     // prompt("","details.method = " + details.method);
     // prompt("","details.url = " + details.url);
        xmlhttp.open(details.method, details.url);
        if (details.headers) {
            for (var prop in details.headers) {
                xmlhttp.setRequestHeader(prop, details.headers[prop]);
            }
        }
    }
    catch (e) {
     // クロスサイトの場合は、C# 側で実装した XmlHttpRequest() 相当のメソッドを呼び出すことで対応
     // prompt("","xmlhttp.open: 例外発生!!");
         _tb_details = details;
        responseTextString = extern.XmlHttpRequestEx(details.method, details.url, details.data);
        return;
    }

    xmlhttp.send(details.data);
}

function TB_readyStateChange()
{
 // prompt("","TB_readyStateChange: called!!");
    responseTextString = extern.XmlHttpRequestEx_result;
    var responseState = {
        responseXML: responseTextString,
        responseText: responseTextString,
        readyState: 4,
        responseHeaders: '200 ok',
        status: 200,
        statusText: 'ok'
    }
    _tb_details["onload"](responseState);
}

function GM_setValue(name,value) {
    return extern.setValue(_tb_scriptName,name,value);
}

function GM_getValue() {
    if (arguments.length==2) {
        return extern.getValue(_tb_scriptName,arguments[0],arguments[1]);
    } else {
        return extern.getValue(_tb_scriptName,arguments[0],undefined);
    }
}

function GM_log() {
    if (arguments.length==3) {
        return extern.log(arguments[0],arguments[1],arguments[2]);
    }
    else if (arguments.length==2) {
        return extern.log(_tb_scriptName,arguments[0],arguments[1]);
    }
    else {
        return extern.log(_tb_scriptName,arguments[0],0);
    }
}

function GM_addStyle(cssText) {
    document.createStyleSheet().cssText = cssText;
}

function GM_openInTab(url) {
    window.open(url, "_blank");
}

GM_log(_tb_scriptName, "Executing script '" + _tb_scriptName + "'", 0);
